﻿using System.Collections.Generic;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using PortalWeb.Business.Entity;
using PortalWeb.Core.IDao;
using PortalWeb.Service;

namespace PortalWeb.Business.Manager
{
    public class IdentityManager
    {
        private readonly IRoleStore<IdentityRole> _roleStore;
        private readonly IUserStore<IdentityUser> _userStore;

        public IdentityManager(IRoleStore<IdentityRole> roleStore, IUserStore<IdentityUser> userStore)
        {
            this._roleStore = roleStore;
            this._userStore = userStore;
        }

        // 判斷角色是否已在存在
        public bool RoleExists(string name)
        {
            var rm = new RoleManager<IdentityRole>(_roleStore);
            return rm.RoleExists(name);
        }

        // 新增角色
        public bool CreateRole(string name)
        {
            var rm = new RoleManager<IdentityRole>(_roleStore);
            var idResult = rm.Create(new IdentityRole(name));
            return idResult.Succeeded;
        }

        // 新增角色
        public bool CreateUser(ApplicationUserModel user, string password)
        {
            var um = new UserManager<IdentityUser>(_userStore);
            var idResult = um.Create(user, password);
            return idResult.Succeeded;
        }

        // 將使用者加入角色中
        public bool AddUserToRole(string userId, string roleName)
        {
            var um = new UserManager<IdentityUser>(_userStore);
            var idResult = um.AddToRole(userId, roleName);
            return idResult.Succeeded;
        }

        /// <summary>
        /// 清除使用者的角色设定
        /// </summary>
        /// <param name="userId"></param>
        public void ClearUserRoles(string userId)
        {
            var um = new UserManager<IdentityUser>(_userStore);
            var user = um.FindById(userId);
            var currentRoles = new List<IdentityUserRole>();
            currentRoles.AddRange(user.Roles);
            foreach (var role in currentRoles)
            {
                um.RemoveFromRole(userId, role.RoleId);
            }
        }
    }
}
